<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 
// 
function test1($orderList, $host){
    // array_walk($orderList, 'foo', $host);
    array_walk_recursive($orderList,"foo",$host);
    return $orderList;
}
function foo(&$val, $key, $host) {
    foreach ($val['pics'] as $k => $v) {
        $val['pics'][$k] = $host.$v;
    }
    return $val;
}

function returnInfo($id,$data = array(),$msg = '成功',$status = true,   $code = 200,$db = '')
{
    $rspdata = json_encode([
        'status' => $status,
        'msg' => $msg,
        'data' => $data,
        'code' => $code
    ]);
    if(!$db){
        $db = 'api_log';
    }
    \think\Db::name($db)->where('id',$id)->update([
        'updateTime' => time(),
        'return' => json_encode($data),
        'code' => $code,
        'msg' => $msg,
    ]);
    exit($rspdata);
}


/* 
 * 经典的概率算法， 
 * $proArr是一个预先设置的数组， 
 * 假设数组为：array(100,200,300，400)， 
 * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，  
 * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间， 
 * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。 
 * 这样 筛选到最终，总会有一个数满足要求。 
 * 就相当于去一个箱子里摸东西， 
 * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。 
 * 这个算法简单，而且效率非常 高， 
 * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。 
 */  
function get_rand($proArr) {
    $result = '';    
    //概率数组的总概率精度   
    $proSum = array_sum($proArr);
    //概率数组循环   
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        }else{
            $proSum -= $proCur;
        }
    }
    unset ($proArr);
    return $result;
}
/**
 * 返回信息
 * @param $message
 * @return array
 */
function ret_message($message = "") {
    if ($message == "") return ['result'=>0, 'message'=>''];
    $ret = lang($message);

    if (count($ret) != 2) {
        return ['result'=>-1,'message'=>'未知错误'];
    }
    return array(
        'result'  => $ret[0],
        'message' => $ret[1]
    );
}

/**
 * 发起http请求
 * @param string $url 访问路径
 * @param array $params 参数，该数组多于1个，表示为POST
 * @param int $expire 请求超时时间
 * @param array $extend 请求伪造包头参数
 * @param string $hostIp HOST的地址
 * @return array    返回的为一个请求状态，一个内容
 */
function makeRequest($url, $params = array(), $expire = 0, $extend = array(), $hostIp = '')
{
    if (empty($url)) {
        return array('code' => '100');
    }

    $_curl = curl_init();
    $_header = array(
        'Accept-Language: zh-CN',
        'Connection: Keep-Alive',
        'Cache-Control: no-cache'
    );
    // 方便直接访问要设置host的地址
    if (!empty($hostIp)) {
        $urlInfo = parse_url($url);
        if (empty($urlInfo['host'])) {
            $urlInfo['host'] = substr(DOMAIN, 7, -1);
            $url = "http://{$hostIp}{$url}";
        } else {
            $url = str_replace($urlInfo['host'], $hostIp, $url);
        }
        $_header[] = "Host: {$urlInfo['host']}";
    }

    // 只要第二个参数传了值之后，就是POST的
    if (!empty($params)) {
        curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($_curl, CURLOPT_POST, true);
    }

    if (substr($url, 0, 8) == 'https://') {
        curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    curl_setopt($_curl, CURLOPT_URL, $url);
    curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
    curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);

    if ($expire > 0) {
        curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
        curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
    }

    // 额外的配置
    if (!empty($extend)) {
        curl_setopt_array($_curl, $extend);
    }

    $result['result'] = curl_exec($_curl);
    $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
    $result['info'] = curl_getinfo($_curl);
    if ($result['result'] === false) {
        $result['result'] = curl_error($_curl);
        $result['code'] = -curl_errno($_curl);
    }

    curl_close($_curl);
    return $result;
}

/**
 * 读取/dev/urandom获取随机数
 * @param $len
 * @return mixed|string
 */
function randomFromDev($len) {
    $fp = @fopen('/dev/urandom','rb');
    $result = '';
    if ($fp !== FALSE) {
        $result .= @fread($fp, $len);
        @fclose($fp);
    }
    else
    {
        trigger_error('Can not open /dev/urandom.');
    }
    // convert from binary to string
    $result = base64_encode($result);
    // remove none url chars
    $result = strtr($result, '+/', '-_');

    return substr($result, 0, $len);
}
function digui($arr, $max = null, $re = [], $i = 0, $bak = []) {
    empty($bak) && $bak = $arr;
    if (count($arr) == 0) {
        // 递归结束,返回解析结果集
        if (empty($re)) {
            return [0, []];
        }
        krsort($re);
        foreach ($re as $k1 => $v1) {
            // 将序列转换为数字
            foreach ($v1 as $k2 => $v2) {
                $v1[$k2] = $bak[$v2];
            }
            // 最终返回结果
            return [$k1, $v1];
        }
    }

    // 取出当前第一个数
    $x = array_shift($arr);

    // 单元素
    if (!isset($re[$x])) {
        if ($x > $max) {
            $i++;
            return digui($arr, $max, $re, $i, $bak);
        }
        if ($x == $max) {
            $re = [$x => [$x]];
            return digui([], $max, $re, $i, $bak);
        }
        $re[$x] = [$i];
    }

    // 双元素相加
    for ($b = 0; $b < count($arr); $b++) {
        $result = $x + $arr[$b];
        if (!isset($re[$result])) {
            if ($result < $max) {
                $re[$result] = [$i, $i + $b + 1];
            }
            if ($result == $max) {
                $re = [$result => [$i, $i + $b + 1]];
                return digui([], $max, $re, $i, $bak);
            }
        }
    }

    // 多元素相加
    foreach ($re as $k => $v) {
        if (count($v) > 1 && !in_array($i, $v)) {
            $result = $k + $x;
            if (!isset($re[$result])) {
                array_push($v, $i);
                if ($result < $max) {
                    $re[$result] = $v;
                }
                if ($result == $max) {
                    $re = [$result => $v];
                    return digui([], $max, $re, $i, $bak);
                }
            }
        }
    }

    $i++;
    return digui($arr, $max, $re, $i, $bak);
}

function ss1($a,$arr){

        $count = count($arr);
        $array = array();
        for($i=0;$i<$count;$i++){
            $r = $arr[$i];
            unset($arr[$i]);
                $sum = abs(array_sum($arr) - $a);
            $array[$sum][] = $arr;
            $arr[] = $r;
        }
        return $array;
    }

function ss($a,$arr){
$count = count($arr);
$array = array();
for($i=0;$i<$count;$i++){
    $r = $arr[$i];
    unset($arr[$i]);
    $sum = abs(array_sum($arr) - $a);
    $array[$sum][] = $arr;
    $arr[] = $r;
}
return $array;
}
// 测算两点的距离(起点->终点)
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2)
{
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles', 'feet', 'yards', 'kilometers', 'meters');
}

function getDistanceBling($longitude1, $latitude1, $longitude2, $latitude2, $unit = 2, $decimal = 2)
{

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI / 180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if ($unit == 2) {
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);

}

// 应用公共文件
function px($data)
{
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    exit();

}

function returnApi($status = true, $msg = '成功', $data = array(), $code = 200)
{
    $rspdata = json_encode([
        'status' => $status,
        'msg' => $msg,
        'data' => $data,
        'code' => $code
    ]);
    \think\Db::name('driver_api_log')->insert([
        'request' => json_encode(request()->param()),
        'time' => time(),
        'response' => $rspdata,
        'did' => isset($_POST['driverId']) ? $_POST['driverId'] : '',
        'code' => $code,
        'action' => request()->url()
    ]);
    exit($rspdata);
}

function getIdentify($username)
{
    return md5(time() . $username . 'slzd');
}

// 随机生成验证码数字
function randString($len = 4)
{
    $chars = str_repeat('0123456789', $len);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

// 验证码发送方法
function sendSms($smsParams, $TemplateCode, $RecNum, $SignName = '顺路直递', $Extend = null)
{
    // dump($smsParams);
    // dump($TemplateCode);
    // dump($RecNum);
    // dump($SignName);
    // exit;
    $request = new \alidayu\Request\SmsNumSend;
    $client = new \alidayu\AlidayuClient;
    $req = $request->setSmsTemplateCode($TemplateCode)
        ->setRecNum($RecNum)
        ->setSmsParam(json_encode($smsParams))
        ->setSmsFreeSignName($SignName)
        ->setSmsType('normal')
        ->setExtend($Extend);
        // dump($req);
        // exit;
    return $client->execute($req);
}


// 发送推送 {driver_1格式}
function sendPush($opts)
{
    try {
        if (empty($opts['alias'])) {
            return false;
        }
        $Log = [];
        $appKey = '';
        $appSecret = '';
        if ($opts['type'] == 'd') {
            $Log['jpush'] = 'SendD';
            $appKey = config('jPushDriverAppKey');
            $appSecret = config('jPushDriverSecret');
        } else {
            $Log['jpush'] = 'SendC';
            $appKey = config('jPushUserAppKey');
            $appSecret = config('jPushUserSecret');
        }
        $client = new \JPush\Client($appKey, $appSecret);
        // 执行推送信息
        $res = $client->push()
            ->setPlatform(['ios', 'android'])
            ->addAlias($opts['alias'])
            // iOS推送
            ->iosNotification($opts['Content'], [
                'sound' => 'sound',
                'badge' => '+1',
                'extras' => $opts['extras']
            ])
            // 安卓推送
            ->androidNotification($opts['Content'], [
                'title' => $opts['Title'],
                'build_id' => '2',
                'extras' => $opts['extras']
            ])
            ->message(json_encode($opts['data']))
            ->options(['apns_production' => true])
            ->send();

        $Log['msg_id'] = $res['body']['msg_id'];
        $Log['sendno'] = $res['body']['sendno'];
        $Log['rule'] = json_encode($opts['alias']);
        $Log['created_at'] = time();
        $Log['updated_at'] = time();
        return \think\Db::name('jpush_log')->insert($Log);
    } catch (\JPush\Exceptions\APIConnectionException $e) {
        // try something here
        return $e;
    } catch (\JPush\Exceptions\APIRequestException $e) {
        // try something here
        return $e;
    }
}


// 阿里云推送
function aliPush($opts, $type = 'd')
{
    if (empty($opts['alias'])) {
        return false;
    }
    require_once EXTEND_PATH . 'AliPush/aliyun-php-sdk-core/Config.php';
    require_once EXTEND_PATH . 'AliPush/aliyun-php-sdk-push/Alipush.php';
    $client = new \Alipush();
    if (empty($opts)) {
        return false;
    }
    if (empty($opts['code'])) {
        return false;
    }
    if (!empty($opts['alias'])) {
        if (is_array($opts['alias'])) {
            $opts['alias'] = implode(',', $opts['alias']);
        }
        $pushData = [
            'Target' => 'ALIAS',
            'rule' => $opts['alias'],
            'pushType' => 'NOTICE',
            'title' => $opts['title'],
            'body' => $opts['body'],
            'data' => json_encode([
                'code' => $opts['code'],
                'time' => time(),
                'data' => $opts['data']
            ])
        ];
        if ($type == 'd') {
            $pushData['appKey'] = '24592129';
        } elseif ($type == 'c') {
            $pushData['appKey'] = '';
        }
        $result = $client->push($pushData);
        return $result;
    }
}


function ramdomNickname()
{
    $str = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    return 'slsj_' . substr(str_shuffle($str), 1, 4);
}


/**
 * CURL的get方法
 * @return array
 */
function curl_get($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $output = curl_exec($ch);
    $result = json_decode($output, true);
    return $result;
}


/**
 * 生成我的邀请码
 */
function getInviteCode($driverId)
{
    $code = 'D' . $driverId . 'D';
    $code .= randString(10 - strlen($code));
    return $code;
}

// 生成二维码
function createQrCode($url, $label)
{
    $qrCode = new \Endroid\QrCode\QrCode();//´´½¨Éú³É¶þÎ¬Âë¶ÔÏó
    $qrCode->setText($url)
        ->setSize(150)
        ->setPadding(10)
        ->setErrorCorrection('high')
        ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
        ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
        ->setLabel($label)//±êÇ©
        ->setLabelFontSize(10)//±êÇ©ÖÐ×ÖÌåµÄ´óÐ¡
        ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG);
    header("Content-type: image/png");
    return $qrCode->render();
}

/*
 * array
 * */
function DataCheck($data, $rule)
{
    $flag = true;
    $rule = array_flip($rule);
    dump($rule);
    foreach ($data as $key => $value) {
        if (array_key_exists($value, $rule)) {
            continue;
        } else {
            $flag = false;
        }
    }
    unset($key, $value);
    return $flag;
}

/*验证是否有值*/
function ValueCheck($data)
{
    $flag = true;
    foreach ($data as $key => $value) {
        if (isset($value)) {
            continue;
        } else {
            return $flag;
        }
    }
    unset($key, $value);
    return $flag;
}

// 保存用户地理位置
function saveUserLocation($lng, $lat, $mobile, $user_type)
{
    $info['user_type'] = $user_type;// 2是用户 1是司机
    $info['coordinate']['lng'] = (float)$lng;
    $info['coordinate']['lat'] = (float)$lat;
    $M = new \org\MonModel('slzd_pro', 'driver_location');
    $rs = $M->where(array('_id' => $mobile))->find(); //查询是否存在
    if ($rs) {
        //已存在
        if ($M->where(array('_id' => $mobile))->save($info)) {
            return true;
        } else {
            return false;
        }
    } else {
        //不存在
        $info['_id'] = $mobile; //手机号做id
        if ($M->add($info)) {
            return true;
        } else {
            return false;
        }
    }
}

// 附近司机
function nearDriver($lng, $lat, $kilometer = 10)
{
    // 推送给附近的接单者
    $M = new \org\MonModel('slzd_pro', 'driver_location');
    $maxDistance = $kilometer; //起始附近5公里
    $where['geoNear'] = 'driver_location';
    $where['near'] = array((float)$lng, (float)$lat);
    $where['spherical'] = true;
    $where['maxDistance'] = $maxDistance / 6371;
    $where['distanceMultiplier'] = 6371;
    $res = $M->command($where);
    $driver_ids = [];
    $user_mobiles = [];
    if (!empty($res['results'])) {
        foreach ($res['results'] as $key => $val) {
            if (isset($val['obj']['user_type']) && $val['obj']['user_type'] == 2) {
                $user_mobiles[] = $val['obj']['_id'];
            } else {
                $driver_ids[] = $val['obj']['_id'];
            }
        }
    }
    $pushAlias = ['u' => [], 'd' => []];
    if (!empty($driver_ids)) {
        $res = \think\Db::name('driver')->field('alias')->where([
            'driverId' => ['in', $driver_ids]
        ])->select();
        if (!empty($res)) {
            foreach ($res as $key => $val) {
                if (!empty($val['alias'])) {
                    $pushAlias['d'][] = $val['alias'];
                }
            }
        }
    }
    if (!empty($user_mobiles)) {
        $res = \think\Db::name('user')->field('alias')->where([
            'mobile' => ['in', $user_mobiles]
        ])->select();
        if (!empty($res)) {
            foreach ($res as $key => $val) {
                if (!empty($val['alias']))
                    $pushAlias['u'][] = $val['alias'];
            }
        }
    }
    return $pushAlias;
}

function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
function http_get11($url){
    // $host = "http://jisuqgclwz.market.alicloudapi.com";
    // $path = "/illegal/query";
    $method = "GET";
    // $appcode = "ea9b09efdaae4d7e8c2e34a6a22db54c";
    // $headers = array();
    // array_push($headers, "Authorization:APPCODE " . $appcode);
    //发动机号 engineno    220058
    //车架号 frameno    014218
    
    // $querys = "carorg=".$option['carorg']."&engineno=".$option['engineno']."&frameno=".$option['frameno']."&iscity=0&lsnum=".$option['lsnum']."&lsprefix=".$option['lsprefix']."&lstype=02";
    // // echo $querys;exit;
    // $bodys = "";
    // $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if (1 == strpos("$".$url, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $result = curl_exec($curl);
        curl_close($curl);
        if($result){
            return $result;
        }else{
            return false;
        }
}


function http_post($url, $post_data)
{
    $ch = curl_init();// 设置curl
    curl_setopt($ch, CURLOPT_URL, $url);// 获取数据
    curl_setopt($ch, CURLOPT_POST, 1);// 用post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));// 利用curl发送post数据
    $optout = curl_exec($ch);// 执行post
    curl_close($ch);
    return $optout;
}

// 获取月份
function GetMonth($sign = "1")
{
    //得到系统的年月
    $tmp_date = date("Ym");
    //切割出年份
    $tmp_year = substr($tmp_date, 0, 4);
    //切割出月份
    $tmp_mon = substr($tmp_date, 4, 2);
    $tmp_nextmonth = mktime(0, 0, 0, $tmp_mon + 1, 1, $tmp_year);
    $tmp_forwardmonth = mktime(0, 0, 0, $tmp_mon - 1, 1, $tmp_year);
    if ($sign == 0) {
        //得到当前月的下一个月
        return $fm_next_month = date("Ym", $tmp_nextmonth);
    } else {
        //得到当前月的上一个月
        return $fm_forward_month = date("Ym", $tmp_forwardmonth);
    }
}

function getAlias($id, $type)
{
    if ($type == 'u') {
        return \think\Db::name('user')->where(['id' => $id])->value('alias');
    } else if ($type == 'driver') {
        return \think\Db::name('driver')->where(['driverId' => $id])->value('alias');
    }
    return false;
}

